<script setup>
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch} from 'vue'
import router from '@/router/index.js'
import {ElMessage} from 'element-plus'
import useArticleStore from '@/stores/article/index.js'
import {Plus} from "@element-plus/icons-vue"; // 引入 css

const articleStore = useArticleStore()
articleStore.getChannelListAction()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const mode = ref('default')

// 内容 HTML
const valueHtml = ref('<p></p>')

watch(valueHtml, (newValue, oldValue) => {
  console.log('newValue', newValue)
})

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: '/front/upload',
      fieldName: 'file',
      customInsert(res, insertFn) {
        insertFn(res)
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

//返回首页
const backBtn = () => {
  router.back()
}

//自动聚焦文章标题
const inputRef = ref()
const focusInput = () => {
  nextTick(() => {
    inputRef.value.focus()
  })
}
onMounted(() => {
  focusInput()
})

//文章发布
const title = ref()
//分类id
const channelId = ref()

//文件上传
const imageUrl = ref()
//文件上传超过限制执行
const uploadFileOver = () => {
  ElMessage({
    type: 'error',
    message: '文件上传超过数量限制'
  })
}
//放大图片调用此方法
const dialogVisible = ref(false)
const handlePictureCardPreview = () => {
  dialogVisible.value = true
}
//移除文件file调用
const uploadFileRef = ref()
const handleRemove = () => {
  imageUrl.value = ''
}
//图片上传成功时候回调
const successUploadFile = (response) => {
  //清除检验结果
  imageUrl.value = response.data
}

//发布文章
const newsForm = reactive({
  title: '',
  content: '',
  images: '',
  channelId: ''
})

//发布
const publishNewsBtn = () => {
  newsForm.title = title.value
  newsForm.content = valueHtml.value
  newsForm.images = imageUrl.value
  newsForm.channelId = channelId.value
  if (newsForm.title || newsForm.content || newsForm.images || newsForm.channelId) {
    const res = articleStore.saveNews(newsForm)
    ElMessage.success('发布成功')
    //再次调用数据显示
    articleStore.loadIngMoreNews(articleStore.searchParam, articleStore.channelId)
    //跳转首页
    router.push('/home')
  } else {
    ElMessage.error('请完善相关文章信息后在发布')
  }
}

const cancelPublishBtn = () => {
  router.back()
}
</script>

<template>
  <div class="article">
    <div class="header">
      <h2 style="color: #f04142; cursor: pointer" @click="backBtn">头条文章</h2>
      <div class="back-home" @click="backBtn">
        <el-icon>
          <Back/>
        </el-icon>
        <span>发布文章</span>
      </div>
    </div>
    <div class="edit">
      <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
      />
      <el-input
          style="font-size: 22px; border-bottom: 1px solid #ccc; padding-bottom: 20px"
          ref="inputRef"
          size="large"
          v-model="title"
          placeholder="请输入文章标题"
      />
      <Editor
          style="height: 500px; overflow-y: hidden"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
      />
    </div>
    <div class="cover">
      <span>文章封面上传</span>
      <el-upload
          ref="uploadFileRef"
          :limit="1"
          action="/front/upload"
          list-type="picture-card"
          :on-success="successUploadFile"
          :on-exceed="uploadFileOver"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
      >
        <el-icon>
          <Plus/>
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img style="width: 600px" w-full :src="imageUrl" alt="Preview Image"/>
      </el-dialog>
    </div>
    <div class="class-news">
      <span>文章类别</span>
      <el-select v-model="channelId" placeholder="请选择分类" size="default" style="width: 240px">
        <el-option
            v-for="item in articleStore.channelList"
            :key="item.id"
            :label="item.channelName"
            :value="item.id"
        />
      </el-select>
    </div>
    <div class="btn">
      <el-button type="danger" @click="publishNewsBtn">发布文章</el-button>
      <el-button type="danger" @click="cancelPublishBtn">取消发布</el-button>
    </div>
  </div>
</template>

<style scoped lang="less">
.article {
  padding-bottom: 50px;
  background-color: #f5f6f7;

  .header {
    display: flex;
    align-items: center;
    padding: 0 62px;
    height: 64px;

    .back-home {
      display: flex;
      align-items: center;
      margin-left: 200px;
      cursor: pointer;

      span {
        margin-left: 20px;
        font-weight: 700;
      }
    }

    .el-icon {
      background-color: rgb(245, 245, 245);
      border-radius: 50%;
      width: 24px;
      height: 24px;
      color: #222;
    }
  }

  .edit {
    background-color: white;
    margin: 0 auto;
    width: 800px;
    border: 1px solid #ccc;

    :deep(.el-input__wrapper) {
      box-shadow: none;
    }

    .el-input {
      margin-top: 20px;
    }
  }

  .edit-detail {
    margin: 0 auto;
    width: 800px;
  }

  .cover {
    width: 800px;
    display: flex;
    margin: 0 auto;
    margin-top: 20px;

    span {
      margin-right: 40px;
    }
  }

  .class-news {
    margin: 20px auto;
    width: 800px;

    span {
      margin-right: 40px;
    }
  }

  .btn {
    display: flex;
    margin: 20px auto;
    width: 800px;
    display: flex;
    justify-content: space-around;
  }
}
</style>
